package com.wfh.aiagent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wfh.aiagent.model.User;
import com.wfh.aiagent.model.UserLoginRequest;
import com.wfh.aiagent.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Size;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Title: UserController
 * @Author wangfenghuan
 * @Package com.wfh.aiagent.controller
 * @Date 2025/10/7 10:37
 * @description: 用户控制器
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {


    @Resource
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<Object> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        // 参数校验
        if (StringUtils.isAnyEmpty(userAccount, userPassword)){
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("msg", "参数错误");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); // 400
        }

        // 查询用户
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getUserAccount, userAccount)
                .eq(User::getUserPassword, userPassword);
        User one = userService.getOne(queryWrapper);

        // 用户不存在
        if (one == null) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("msg", "用户名或密码错误");
            errorResponse.put("data", null);
            return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED); // 401
        }

        // 登录成功，设置 Session
        request.getSession().setAttribute("user_login", one);

        // 返回成功响应
        Map<String, Object> successResponse = new HashMap<>();
        successResponse.put("msg", "登录成功");
        successResponse.put("data", one);
        return new ResponseEntity<>(successResponse, HttpStatus.OK); // 200 ✅
    }


}
